home *** CD-ROM | disk | FTP | other *** search
/ Revista do CD-ROM 118 / cd-rom 118.iso / aplic / open / openofficeorg3.cab / site.py < prev    next >
Encoding:
Python Source  |  2005-02-15  |  12.1 KB  |  375 lines

  1. """Append module search paths for third-party packages to sys.path.
  2.  
  3. ****************************************************************
  4. * This module is automatically imported during initialization. *
  5. ****************************************************************
  6.  
  7. In earlier versions of Python (up to 1.5a3), scripts or modules that
  8. needed to use site-specific modules would place ``import site''
  9. somewhere near the top of their code.  Because of the automatic
  10. import, this is no longer necessary (but code that does it still
  11. works).
  12.  
  13. This will append site-specific paths to the module search path.  On
  14. Unix, it starts with sys.prefix and sys.exec_prefix (if different) and
  15. appends lib/python<version>/site-packages as well as lib/site-python.
  16. On other platforms (mainly Mac and Windows), it uses just sys.prefix
  17. (and sys.exec_prefix, if different, but this is unlikely).  The
  18. resulting directories, if they exist, are appended to sys.path, and
  19. also inspected for path configuration files.
  20.  
  21. A path configuration file is a file whose name has the form
  22. <package>.pth; its contents are additional directories (one per line)
  23. to be added to sys.path.  Non-existing directories (or
  24. non-directories) are never added to sys.path; no directory is added to
  25. sys.path more than once.  Blank lines and lines beginning with
  26. '#' are skipped. Lines starting with 'import' are executed.
  27.  
  28. For example, suppose sys.prefix and sys.exec_prefix are set to
  29. /usr/local and there is a directory /usr/local/lib/python1.5/site-packages
  30. with three subdirectories, foo, bar and spam, and two path
  31. configuration files, foo.pth and bar.pth.  Assume foo.pth contains the
  32. following:
  33.  
  34.   # foo package configuration
  35.   foo
  36.   bar
  37.   bletch
  38.  
  39. and bar.pth contains:
  40.  
  41.   # bar package configuration
  42.   bar
  43.  
  44. Then the following directories are added to sys.path, in this order:
  45.  
  46.   /usr/local/lib/python1.5/site-packages/bar
  47.   /usr/local/lib/python1.5/site-packages/foo
  48.  
  49. Note that bletch is omitted because it doesn't exist; bar precedes foo
  50. because bar.pth comes alphabetically before foo.pth; and spam is
  51. omitted because it is not mentioned in either path configuration file.
  52.  
  53. After these path manipulations, an attempt is made to import a module
  54. named sitecustomize, which can perform arbitrary additional
  55. site-specific customizations.  If this import fails with an
  56. ImportError exception, it is silently ignored.
  57.  
  58. """
  59.  
  60. import sys, os
  61.  
  62.  
  63. def makepath(*paths):
  64.     dir = os.path.abspath(os.path.join(*paths))
  65.     return dir, os.path.normcase(dir)
  66.  
  67. for m in sys.modules.values():
  68.     if hasattr(m, "__file__") and m.__file__:
  69.         m.__file__ = os.path.abspath(m.__file__)
  70. del m
  71.  
  72. # This ensures that the initial path provided by the interpreter contains
  73. # only absolute pathnames, even if we're running from the build directory.
  74. L = []
  75. _dirs_in_sys_path = {}
  76. dir = dircase = None  # sys.path may be empty at this point
  77. for dir in sys.path:
  78.     # Filter out duplicate paths (on case-insensitive file systems also
  79.     # if they only differ in case); turn relative paths into absolute
  80.     # paths.
  81.     dir, dircase = makepath(dir)
  82.     if not dircase in _dirs_in_sys_path:
  83.         L.append(dir)
  84.         _dirs_in_sys_path[dircase] = 1
  85. sys.path[:] = L
  86. del dir, dircase, L
  87.  
  88. # Append ./build/lib.<platform> in case we're running in the build dir
  89. # (especially for Guido :-)
  90. # XXX This should not be part of site.py, since it is needed even when
  91. # using the -S option for Python.  See http://www.python.org/sf/586680
  92. if (os.name == "posix" and sys.path and
  93.     os.path.basename(sys.path[-1]) == "Modules"):
  94.     from distutils.util import get_platform
  95.     s = "build/lib.%s-%.3s" % (get_platform(), sys.version)
  96.     s = os.path.join(os.path.dirname(sys.path[-1]), s)
  97.     sys.path.append(s)
  98.     del get_platform, s
  99.  
  100. def _init_pathinfo():
  101.     global _dirs_in_sys_path
  102.     _dirs_in_sys_path = d = {}
  103.     for dir in sys.path:
  104.         if dir and not os.path.isdir(dir):
  105.             continue
  106.         dir, dircase = makepath(dir)
  107.         d[dircase] = 1
  108.  
  109. def addsitedir(sitedir):
  110.     global _dirs_in_sys_path
  111.     if _dirs_in_sys_path is None:
  112.         _init_pathinfo()
  113.         reset = 1
  114.     else:
  115.         reset = 0
  116.     sitedir, sitedircase = makepath(sitedir)
  117.     if not sitedircase in _dirs_in_sys_path:
  118.         sys.path.append(sitedir)        # Add path component
  119.     try:
  120.         names = os.listdir(sitedir)
  121.     except os.error:
  122.         return
  123.     names.sort()
  124.     for name in names:
  125.         if name[-4:] == os.extsep + "pth":
  126.             addpackage(sitedir, name)
  127.     if reset:
  128.         _dirs_in_sys_path = None
  129.  
  130. def addpackage(sitedir, name):
  131.     global _dirs_in_sys_path
  132.     if _dirs_in_sys_path is None:
  133.         _init_pathinfo()
  134.         reset = 1
  135.     else:
  136.         reset = 0
  137.     fullname = os.path.join(sitedir, name)
  138.     try:
  139.         f = open(fullname)
  140.     except IOError:
  141.         return
  142.     while 1:
  143.         dir = f.readline()
  144.         if not dir:
  145.             break
  146.         if dir[0] == '#':
  147.             continue
  148.         if dir.startswith("import"):
  149.             exec dir
  150.             continue
  151.         dir = dir.rstrip()
  152.         dir, dircase = makepath(sitedir, dir)
  153.         if not dircase in _dirs_in_sys_path and os.path.exists(dir):
  154.             sys.path.append(dir)
  155.             _dirs_in_sys_path[dircase] = 1
  156.     if reset:
  157.         _dirs_in_sys_path = None
  158.  
  159. prefixes = [sys.prefix]
  160. sitedir = None # make sure sitedir is initialized because of later 'del'
  161. if sys.exec_prefix != sys.prefix:
  162.     prefixes.append(sys.exec_prefix)
  163. for prefix in prefixes:
  164.     if prefix:
  165.         if sys.platform in ('os2emx', 'riscos'):
  166.             sitedirs = [os.path.join(prefix, "Lib", "site-packages")]
  167.         elif os.sep == '/':
  168.             sitedirs = [os.path.join(prefix,
  169.                                      "lib",
  170.                                      "python" + sys.version[:3],
  171.                                      "site-packages"),
  172.                         os.path.join(prefix, "lib", "site-python")]
  173.         else:
  174.             sitedirs = [prefix, os.path.join(prefix, "lib", "site-packages")]
  175.         if sys.platform == 'darwin':
  176.             # for framework builds *only* we add the standard Apple
  177.             # locations. Currently only per-user, but /Library and
  178.             # /Network/Library could be added too
  179.             if 'Python.framework' in prefix:
  180.                 home = os.environ.get('HOME')
  181.                 if home:
  182.                     sitedirs.append(
  183.                         os.path.join(home,
  184.                                      'Library',
  185.                                      'Python',
  186.                                      sys.version[:3],
  187.                                      'site-packages'))
  188.         for sitedir in sitedirs:
  189.             if os.path.isdir(sitedir):
  190.                 addsitedir(sitedir)
  191. del prefix, sitedir
  192.  
  193. _dirs_in_sys_path = None
  194.  
  195.  
  196. # the OS/2 EMX port has optional extension modules that do double duty
  197. # as DLLs (and must use the .DLL file extension) for other extensions.
  198. # The library search path needs to be amended so these will be found
  199. # during module import.  Use BEGINLIBPATH so that these are at the start
  200. # of the library search path.
  201. if sys.platform == 'os2emx':
  202.     dllpath = os.path.join(sys.prefix, "Lib", "lib-dynload")
  203.     libpath = os.environ['BEGINLIBPATH'].split(';')
  204.     if libpath[-1]:
  205.         libpath.append(dllpath)
  206.     else:
  207.         libpath[-1] = dllpath
  208.     os.environ['BEGINLIBPATH'] = ';'.join(libpath)
  209.  
  210.  
  211. # Define new built-ins 'quit' and 'exit'.
  212. # These are simply strings that display a hint on how to exit.
  213. if os.sep == ':':
  214.     exit = 'Use Cmd-Q to quit.'
  215. elif os.sep == '\\':
  216.     exit = 'Use Ctrl-Z plus Return to exit.'
  217. else:
  218.     exit = 'Use Ctrl-D (i.e. EOF) to exit.'
  219. import __builtin__
  220. __builtin__.quit = __builtin__.exit = exit
  221. del exit
  222.  
  223. # interactive prompt objects for printing the license text, a list of
  224. # contributors and the copyright notice.
  225. class _Printer:
  226.     MAXLINES = 23
  227.  
  228.     def __init__(self, name, data, files=(), dirs=()):
  229.         self.__name = name
  230.         self.__data = data
  231.         self.__files = files
  232.         self.__dirs = dirs
  233.         self.__lines = None
  234.  
  235.     def __setup(self):
  236.         if self.__lines:
  237.             return
  238.         data = None
  239.         for dir in self.__dirs:
  240.             for file in self.__files:
  241.                 file = os.path.join(dir, file)
  242.                 try:
  243.                     fp = open(file)
  244.                     data = fp.read()
  245.                     fp.close()
  246.                     break
  247.                 except IOError:
  248.                     pass
  249.             if data:
  250.                 break
  251.         if not data:
  252.             data = self.__data
  253.         self.__lines = data.split('\n')
  254.         self.__linecnt = len(self.__lines)
  255.  
  256.     def __repr__(self):
  257.         self.__setup()
  258.         if len(self.__lines) <= self.MAXLINES:
  259.             return "\n".join(self.__lines)
  260.         else:
  261.             return "Type %s() to see the full %s text" % ((self.__name,)*2)
  262.  
  263.     def __call__(self):
  264.         self.__setup()
  265.         prompt = 'Hit Return for more, or q (and Return) to quit: '
  266.         lineno = 0
  267.         while 1:
  268.             try:
  269.                 for i in range(lineno, lineno + self.MAXLINES):
  270.                     print self.__lines[i]
  271.             except IndexError:
  272.                 break
  273.             else:
  274.                 lineno += self.MAXLINES
  275.                 key = None
  276.                 while key is None:
  277.                     key = raw_input(prompt)
  278.                     if key not in ('', 'q'):
  279.                         key = None
  280.                 if key == 'q':
  281.                     break
  282.  
  283. __builtin__.copyright = _Printer("copyright", sys.copyright)
  284. if sys.platform[:4] == 'java':
  285.     __builtin__.credits = _Printer(
  286.         "credits",
  287.         "Jython is maintained by the Jython developers (www.jython.org).")
  288. else:
  289.     __builtin__.credits = _Printer("credits", """\
  290. Thanks to CWI, CNRI, BeOpen.com, Zope Corporation and a cast of thousands
  291. for supporting Python development.  See www.python.org for more information.""")
  292. here = os.path.dirname(os.__file__)
  293. __builtin__.license = _Printer(
  294.     "license", "See http://www.python.org/%.3s/license.html" % sys.version,
  295.     ["LICENSE.txt", "LICENSE"],
  296.     [os.path.join(here, os.pardir), here, os.curdir])
  297.  
  298.  
  299. # Define new built-in 'help'.
  300. # This is a wrapper around pydoc.help (with a twist).
  301.  
  302. class _Helper:
  303.     def __repr__(self):
  304.         return "Type help() for interactive help, " \
  305.                "or help(object) for help about object."
  306.     def __call__(self, *args, **kwds):
  307.         import pydoc
  308.         return pydoc.help(*args, **kwds)
  309.  
  310. __builtin__.help = _Helper()
  311.  
  312.  
  313. # On Windows, some default encodings are not provided
  314. # by Python (e.g. "cp932" in Japanese locale), while they
  315. # are always available as "mbcs" in each locale.
  316. # Make them usable by aliasing to "mbcs" in such a case.
  317.  
  318. if sys.platform == 'win32':
  319.     import locale, codecs
  320.     enc = locale.getdefaultlocale()[1]
  321.     if enc.startswith('cp'):            # "cp***" ?
  322.         try:
  323.             codecs.lookup(enc)
  324.         except LookupError:
  325.             import encodings
  326.             encodings._cache[enc] = encodings._unknown
  327.             encodings.aliases.aliases[enc] = 'mbcs'
  328.  
  329. # Set the string encoding used by the Unicode implementation.  The
  330. # default is 'ascii', but if you're willing to experiment, you can
  331. # change this.
  332.  
  333. encoding = "ascii" # Default value set by _PyUnicode_Init()
  334.  
  335. if 0:
  336.     # Enable to support locale aware default string encodings.
  337.     import locale
  338.     loc = locale.getdefaultlocale()
  339.     if loc[1]:
  340.         encoding = loc[1]
  341.  
  342. if 0:
  343.     # Enable to switch off string to Unicode coercion and implicit
  344.     # Unicode to string conversion.
  345.     encoding = "undefined"
  346.  
  347. if encoding != "ascii":
  348.     # On Non-Unicode builds this will raise an AttributeError...
  349.     sys.setdefaultencoding(encoding) # Needs Python Unicode build !
  350.  
  351. #
  352. # Run custom site specific code, if available.
  353. #
  354. try:
  355.     import sitecustomize
  356. except ImportError:
  357.     pass
  358.  
  359. #
  360. # Remove sys.setdefaultencoding() so that users cannot change the
  361. # encoding after initialization.  The test for presence is needed when
  362. # this module is run as a script, because this code is executed twice.
  363. #
  364. if hasattr(sys, "setdefaultencoding"):
  365.     del sys.setdefaultencoding
  366.  
  367. def _test():
  368.     print "sys.path = ["
  369.     for dir in sys.path:
  370.         print "    %s," % `dir`
  371.     print "]"
  372.  
  373. if __name__ == '__main__':
  374.     _test()
  375.